let fs = require('fs')

let loadTokenFromFile = function loadTokenFromFile() {
    if(!fs.existsSync('files/token')){
        return null;      
    }
    let tokenInfo = JSON.parse(fs.readFileSync('files/token'));
    if(tokenInfo.time + tokenInfo.expires_in * 1000 >  Date.now())
    {
        return tokenInfo.access_token;
    }
    return null;
}

let loadMyInfoFromFile =  function loadMyInfoFromFile(){
    if(!fs.existsSync('files/myInfo')){
        return null;      
    }
    let myInfo = JSON.parse(fs.readFileSync('files/myInfo'));    
    return myInfo;
}

let saveToken2File =  function saveToken2File(response){
    var obj = JSON.parse(response);
    obj.time = Date.now();
    fs.writeFileSync('files/token', JSON.stringify(obj));
}

let saveMyInfo2File =  function saveMyInfo2File(myInfo){
    fs.writeFileSync('files/myInfo', JSON.stringify(myInfo));
}

exports.loadTokenFromFile = loadTokenFromFile;
exports.loadMyInfoFromFile = loadMyInfoFromFile;
exports.saveToken2File = saveToken2File;
exports.saveMyInfo2File = saveMyInfo2File;